package com.lucifer.treasure.config;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;

public class ConfigHandler {
    
    private static final Map<String, Boolean> BOOLEAN_VALUES = new HashMap<>();
    private static final Map<String, Integer> INTEGER_VALUES = new HashMap<>();
    private static Path configFile;
    
    // 附魔启用状态配置
    private static final Map<String, BooleanValue> ENCHANT_ENABLED = new HashMap<>();
    
    public static void init(Path configDir) {
        configFile = configDir.resolve("lucifer-treasure-enchants.toml");
        loadConfig();
    }
    
    public static BooleanValue booleanValue(String key, boolean defaultValue) {
        BOOLEAN_VALUES.putIfAbsent(key, defaultValue);
        return new BooleanValue(key, defaultValue);
    }
    
    public static IntValue intValue(String key, int defaultValue) {
        INTEGER_VALUES.putIfAbsent(key, defaultValue);
        return new IntValue(key, defaultValue);
    }
    
    /**
     * 获取或创建附魔启用配置
     * @param enchantName 附魔名称
     * @param defaultEnabled 默认启用状态
     * @return BooleanValue配置对象
     */
    public static BooleanValue enchantEnabled(String enchantName, boolean defaultEnabled) {
        String key = "enchant." + enchantName + ".enabled";
        if (!ENCHANT_ENABLED.containsKey(enchantName)) {
            ENCHANT_ENABLED.put(enchantName, booleanValue(key, defaultEnabled));
        }
        return ENCHANT_ENABLED.get(enchantName);
    }
    
    /**
     * 检查指定附魔是否启用
     * @param enchantName 附魔名称
     * @return true表示启用，false表示禁用
     */
    public static boolean isEnchantEnabled(String enchantName) {
        BooleanValue config = ENCHANT_ENABLED.get(enchantName);
        if (config != null) {
            return config.get();
        }
        // 如果没有配置，默认启用
        return true;
    }
    
    /**
     * 设置附魔启用状态
     * @param enchantName 附魔名称
     * @param enabled 启用状态
     */
    public static void setEnchantEnabled(String enchantName, boolean enabled) {
        BooleanValue config = ENCHANT_ENABLED.get(enchantName);
        if (config != null) {
            config.set(enabled);
        }
    }
    
    /**
     * 获取所有附魔的启用状态
     * @return 附魔名称和启用状态的映射
     */
    public static Map<String, Boolean> getAllEnchantEnabledStatus() {
        Map<String, Boolean> status = new HashMap<>();
        for (Map.Entry<String, BooleanValue> entry : ENCHANT_ENABLED.entrySet()) {
            status.put(entry.getKey(), entry.getValue().get());
        }
        return status;
    }
    
    private static void loadConfig() {
        if (Files.exists(configFile)) {
            try {
                String content = Files.readString(configFile);
                parseTomlConfig(content);
            } catch (Exception e) {
                System.err.println("配置文件加载失败，将使用默认配置: " + e.getMessage());
                saveConfig();
            }
        } else {
            saveConfig();
        }
    }
    
    /**
     * 简单的TOML解析器（仅支持我们需要的格式）
     */
    private static void parseTomlConfig(String content) {
        String[] lines = content.split("\n");
        String currentSection = "";
        
        for (String line : lines) {
            line = line.trim();
            
            // 跳过注释和空行
            if (line.isEmpty() || line.startsWith("#")) {
                continue;
            }
            
            // 检查是否是节（section）
            if (line.startsWith("[") && line.endsWith("]")) {
                currentSection = line.substring(1, line.length() - 1);
                continue;
            }
            
            // 解析键值对
            if (line.contains("=")) {
                String[] parts = line.split("=", 2);
                if (parts.length == 2) {
                    String key = parts[0].trim();
                    String value = parts[1].trim();
                    
                    // 处理不同节的配置
                    if ("enchantments".equals(currentSection)) {
                        parseEnchantmentConfig(key, value);
                    } else if ("general".equals(currentSection)) {
                        parseGeneralConfig(key, value);
                    }
                }
            }
        }
    }
    
    private static void parseEnchantmentConfig(String key, String value) {
        // 移除注释部分
        if (value.contains("#")) {
            value = value.substring(0, value.indexOf("#")).trim();
        }
        
        // 解析布尔值
        boolean boolValue = "true".equalsIgnoreCase(value.trim());
        String fullKey = "enchant." + key + ".enabled";
        BOOLEAN_VALUES.put(fullKey, boolValue);
    }
    
    private static void parseGeneralConfig(String key, String value) {
        // 移除注释部分
        if (value.contains("#")) {
            value = value.substring(0, value.indexOf("#")).trim();
        }
        
        // 尝试解析为布尔值
        if ("true".equalsIgnoreCase(value) || "false".equalsIgnoreCase(value)) {
            BOOLEAN_VALUES.put(key, Boolean.parseBoolean(value));
        }
        // 尝试解析为整数
        else {
            try {
                int intValue = Integer.parseInt(value.trim());
                INTEGER_VALUES.put(key, intValue);
            } catch (NumberFormatException e) {
                // 忽略无法解析的值
            }
        }
    }
    
    public static void saveConfig() {
        try {
            Files.createDirectories(configFile.getParent());
            
            StringBuilder toml = new StringBuilder();
            
            // 添加文件头注释
            toml.append("# 路西法的宝藏 模组配置文件\n");
            toml.append("# ====================================\n");
            toml.append("# 版本: 1.1.0\n");
            toml.append("# 修改配置后需要重启游戏才能生效\n");
            toml.append("# 使用 true 启用附魔，false 禁用附魔\n");
            toml.append("\n");
            
            // 附魔配置节
            toml.append("[enchantments]\n");
            toml.append("# 附魔启用/禁用控制\n");
            toml.append("# true = 启用，false = 禁用\n");
            toml.append("\n");
            
            // 按类别组织附魔
            toml.append("# === 工具类附魔 ===\n");
            appendEnchantConfig(toml, "auto_smelt", "自动熔炼 - 挖掘时自动熔炼矿物");
            appendEnchantConfig(toml, "experience_boost", "经验提升 - 大幅增加经验获取");
            appendEnchantConfig(toml, "excavation", "连锁挖掘 - 连锁挖掘相同类型的矿物");
            appendEnchantConfig(toml, "magnet", "磁力 - 自动吸引掉落物");
            toml.append("\n");
            
            toml.append("# === 战斗类附魔 ===\n");
            appendEnchantConfig(toml, "reach", "延伸打击 - 增加攻击距离");
            appendEnchantConfig(toml, "venom", "毒液 - 攻击时施加中毒效果");
            appendEnchantConfig(toml, "beheading", "斩首 - 增加头颅掉落概率");
            appendEnchantConfig(toml, "disarm", "缴械 - 有概率让敌人掉落武器");
            appendEnchantConfig(toml, "life_leech", "生命汲取 - 攻击时恢复生命值");
            toml.append("\n");
            
            toml.append("# === 防护类附魔 ===\n");
            appendEnchantConfig(toml, "block_reach", "方块范围扩展 - 增加方块交互距离");
            appendEnchantConfig(toml, "steady", "稳定 - 减少击退效果");
            appendEnchantConfig(toml, "traveller", "旅行者 - 减少环境伤害");
            appendEnchantConfig(toml, "laststand", "最后一击 - 濒死时消耗经验恢复生命值");
            toml.append("\n");
            
            toml.append("# === 移动类附魔 ===\n");
            appendEnchantConfig(toml, "step", "自动台阶 - 自动跨越一格高的方块");
            appendEnchantConfig(toml, "multijump", "多重跳跃 - 允许空中多段跳跃");
            toml.append("\n");
            
            toml.append("# === 远程类附魔 ===\n");
            appendEnchantConfig(toml, "multibow", "多重射击 - 发射多支箭矢");
            appendEnchantConfig(toml, "quickdraw", "快速拉弦 - 加快拉弦速度");
            toml.append("\n");
            
            toml.append("# === 生活类附魔 ===\n");
            appendEnchantConfig(toml, "growth", "成长 - 加速作物和树木生长");
            appendEnchantConfig(toml, "beekeeper", "养蜂人 - 免疫蜜蜂攻击并提高蜂蜜产量");
            appendEnchantConfig(toml, "ender_pearl", "末影珍珠 - 右键使用时传送");
            toml.append("\n");
            
            toml.append("# === 特殊类附魔 ===\n");
            appendEnchantConfig(toml, "sword_aura", "御剑术 - 自动召唤剑气攻击范围内的敌人");
            toml.append("\n");
            
            toml.append("# === 诅咒类附魔 ===\n");
            appendEnchantConfig(toml, "gloom_curse", "阴暗诅咒 - 诅咒附魔，攻击时几率使对手获得负面效果");
            toml.append("\n");
            
            // 通用配置节（如果有的话）
            if (!BOOLEAN_VALUES.isEmpty() || !INTEGER_VALUES.isEmpty()) {
                boolean hasGeneralConfig = false;
                for (String key : BOOLEAN_VALUES.keySet()) {
                    if (!key.startsWith("enchant.")) {
                        hasGeneralConfig = true;
                        break;
                    }
                }
                if (!hasGeneralConfig && !INTEGER_VALUES.isEmpty()) {
                    hasGeneralConfig = true;
                }
                
                if (hasGeneralConfig) {
                    toml.append("[general]\n");
                    toml.append("# 通用配置选项\n");
                    
            for (Map.Entry<String, Boolean> entry : BOOLEAN_VALUES.entrySet()) {
                        if (!entry.getKey().startsWith("enchant.")) {
                            toml.append(entry.getKey()).append(" = ").append(entry.getValue()).append("\n");
                        }
            }
                    
            for (Map.Entry<String, Integer> entry : INTEGER_VALUES.entrySet()) {
                        toml.append(entry.getKey()).append(" = ").append(entry.getValue()).append("\n");
                    }
                }
            }
            
            Files.writeString(configFile, toml.toString());
            
        } catch (IOException e) {
            System.err.println("配置文件保存失败: " + e.getMessage());
        }
    }
    
    private static void appendEnchantConfig(StringBuilder toml, String enchantName, String description) {
        // 优先从BOOLEAN_VALUES中读取配置
        String key = "enchant." + enchantName + ".enabled";
        boolean enabled = BOOLEAN_VALUES.getOrDefault(key, true);
        toml.append(enchantName).append(" = ").append(enabled)
            .append("  # ").append(description).append("\n");
    }
    
    public static class BooleanValue {
        private final String key;
        private final boolean defaultValue;
        
        public BooleanValue(String key, boolean defaultValue) {
            this.key = key;
            this.defaultValue = defaultValue;
        }
        
        public boolean get() {
            return BOOLEAN_VALUES.getOrDefault(key, defaultValue);
        }
        
        public void set(boolean value) {
            BOOLEAN_VALUES.put(key, value);
            saveConfig();
        }
    }
    
    public static class IntValue {
        private final String key;
        private final int defaultValue;
        
        public IntValue(String key, int defaultValue) {
            this.key = key;
            this.defaultValue = defaultValue;
        }
        
        public int get() {
            return INTEGER_VALUES.getOrDefault(key, defaultValue);
        }
        
        public void set(int value) {
            INTEGER_VALUES.put(key, value);
            saveConfig();
        }
    }
} 